<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('update:visible', $event)"
    :title="isEdit ? '编辑产品' : '新增产品'"
    width="700px"
    :before-close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="产品名称" prop="productName">
        <el-input v-model="form.productName" />
      </el-form-item>
      <el-form-item label="英文名" prop="englishName">
        <el-input v-model="form.englishName" />
      </el-form-item>
      <el-form-item label="价格" prop="price">
        <el-input-number v-model="form.price" :min="0" :precision="2" />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <!-- <el-input v-model="form.category" /> -->
        <el-select v-model="form.category" placeholder="全部分类" clearable style="width: 140px;">
          <el-option v-for="item in selectOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="适用场景" prop="scenarios">
        <el-input v-model="form.scenarios" placeholder="多个用逗号分隔" />
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-input v-model="form.tags" placeholder="多个用逗号分隔" />
      </el-form-item>
   
      <el-form-item label="图片集" prop="imageUrls">
        <el-upload
          class="upload-demo"
          list-type="picture-card"
          :file-list="imageUpload.fileList"
          :auto-upload="false"
          :on-change="imageUpload.handleSelect"
          :on-remove="imageUpload.handleRemove"
          multiple
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="详情图" prop="detailUrls">
        <el-upload
          class="upload-demo"
          list-type="picture-card"
          :file-list="detailUpload.fileList"
          :auto-upload="false"
          :on-change="detailUpload.handleSelect"
          :on-remove="detailUpload.handleRemove"
          multiple
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="form.description" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch ,onMounted} from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useFileUpload } from '@/composables/useFileUpload'
import { fileBaseUrl } from '@/apis/files'
import { getCategoryList } from '@/apis/admin/category'

const selectOptions = ref([])
const props = defineProps({
  visible: Boolean,
  product: { type: Object, default: () => ({}) },
  isEdit: Boolean
})
const emit = defineEmits(['update:visible', 'submit'])

const formRef = ref(null)
const loading = ref(false)

// 获取所有分类
const fetchCategories = async () => {
  try {
    const res = await getCategoryList({ size: 1000 }) // 获取所有分类
    if (res.code === '0') {
      selectOptions.value = res.data.records.map(item => ({
        value: item.categoryName,
        label: item.categoryName
      }))
    }
  } catch (e) {
    console.error('获取分类失败:', e)
  }
}

onMounted(() => {
  fetchCategories()
})

const form = reactive({
  productId: '',
  productName: '',
  englishName: '',
  price: 0,
  category: '',
  scenarios: '',
  tags: '',
  coverImage: '',
  imageUrls: '',
  detailUrls: '',
  description: ''
})

const rules = {
  productName: [{ required: true, message: '请输入产品名称', trigger: 'blur' }],
  englishName: [{ required: true, message: '请输入英文名', trigger: 'blur' }],
  price: [{ required: true, message: '请输入价格', trigger: 'blur' }],
  category: [{ required: true, message: '请输入分类', trigger: 'blur' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }]
}

// 通用图片上传hook
function useMultiUpload(basePath, formKey, label) {
  const {
    fileList,
    uploadFile,
    deleteFile,
    clearFiles
  } = useFileUpload()

  // fileList赋值
  function setFileList(urls) {
    fileList.value = urls
      ? urls.split(',').map((url, idx) => ({
          url: fileBaseUrl() + url,
          name: `${label}${idx + 1}`
        }))
      : []
  }

  // 选择/移除
  function handleSelect(file, list) {
    fileList.value = list.map(f => ({
      name: f.name,
      url: f.url || f.preview || (f.response ? f.response.url : ''),
      raw: f.raw
    }))
    updateForm()
  }
  function handleRemove(file, list) {
    if (file.url) {
      const rel = extractRelativePath(file.url, basePath)
      deleteFile(basePath, rel.split('/').pop())
    }
    fileList.value = list
    updateForm()
  }

  // 路径提取
  function extractRelativePath(url, basePath) {
    const idx = url.indexOf(basePath)
    return idx !== -1 ? url.substring(idx) : url
  }

  // 更新form
  function updateForm() {
    form[formKey] = fileList.value
      .map(f => extractRelativePath(f.url, basePath))
      .join(',')
  }

  // 上传
  async function uploadAll() {
    for (let file of fileList.value) {
      if (file.raw && !file.url.startsWith('http')) {
        const result = await uploadFile(basePath, file.raw)
        if (result) file.url = extractRelativePath(result, basePath)
      } else if (file.url && file.url.startsWith('http')) {
        file.url = extractRelativePath(file.url, basePath)
      }
    }
    updateForm()
  }

  return {
    fileList,
    setFileList,
    handleSelect,
    handleRemove,
    uploadAll
  }
}

// 两组图片上传
const imageUpload = useMultiUpload('product/images', 'imageUrls', '图片')
const detailUpload = useMultiUpload('product/details', 'detailUrls', '详情')

watch(() => props.product, (val) => {
  if (val && Object.keys(val).length) {
    Object.assign(form, val)
    imageUpload.setFileList(val.imageUrls)
    detailUpload.setFileList(val.detailUrls)
  } else {
    Object.assign(form, {
      productId: '', productName: '', englishName: '', price: 0, category: '', scenarios: '', tags: '', coverImage: '', imageUrls: '', detailUrls: '', description: ''
    })
    imageUpload.setFileList('')
    detailUpload.setFileList('')
  }
}, { immediate: true })

const handleClose = () => {
  emit('update:visible', false)
  formRef.value?.resetFields()
  imageUpload.fileList.value = []
  detailUpload.fileList.value = []
}

const handleSubmit = async () => {
  await formRef.value.validate()
  loading.value = true
  await imageUpload.uploadAll()
  await detailUpload.uploadAll()
  emit('submit', { ...form })
  loading.value = false
}
</script>

<style scoped>
.cover-preview {
  width: 80px;
  height: 80px;
  object-fit: cover;
  border-radius: 6px;
  border: 1px solid #eee;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 